package techLayer;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/*
 * A controllerclass for the network part of the game.
 * Can setup a connection and add/recieve both moves and player names.
 */
public class NetworkController implements netFace {

	private Socket socket;
	private DataInputStream input;
	private DataOutputStream output;

	@Override
	public void createServer(int port) {
		ServerSocket server;
		try {
			server = new ServerSocket(port);
			socket = server.accept();
			
			System.out.println("Connected!");

		} catch (IOException ex) {
			System.out.println("Failed to establish a connection on the server!");
		}
		initIOStreams();
	}

	@Override
	public void connect(String hostName, int port) {
		try {
			socket = new Socket(hostName, port);
		} catch (UnknownHostException ex) {
			System.out.println("Can't find server!");
		} catch (IOException ex) {
			System.out.println("Error connecting to server!");
		}
		initIOStreams();
	}

	@Override
	public void sendMove(int column) {
		try {
			output.writeInt(column);
		} catch (IOException ex) {
			System.out.println("Error sending move!");
		}
	}

	@Override
	public int recieveMove() {
		int move = -1; // ERROR
        try {
            move = input.readInt();
        } catch (IOException ex) {
            System.out.println("Error recieving move!");
        }
		return move;
	}

	@Override
	public void closeConnection() {
		try {
			socket.close();
		} catch (IOException ex) {
			System.out.println("Error closing socket!");
		}
	}

	private void initIOStreams() {
		try {
			input = new DataInputStream(socket.getInputStream());
			output = new DataOutputStream(socket.getOutputStream());
		} catch (IOException ex) {
			System.out.println("Error binding socket to streams!");
		}
	}

	@Override
	public void sendName(String name) {
		try {
			output.writeUTF(name);
		} catch (IOException ex) {
			System.out.println("Error sending name!");
		}
	}

	@Override
	public String recieveName() {
		String name = "";
		try {
			name = input.readUTF();
		} catch (IOException ex) {
			System.out.println("Error recieving name!");
		}
		return name;
	}
}
